{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "590ccdab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模型在训练集上的预测准确率为： 0.519480608218357\n",
      "模型在测试集上的预测准确率为： 0.47994757514558173\n",
      "套索回归使用的特征数为： 7\n"
     ]
    }
   ],
   "source": [
    "#项目2-例2-9代码\n",
    "\n",
    "#套索回归，参数为0.1\n",
    "#导入 numpy库、糖尿病数据集、套索回归模型及划分样本的方法\n",
    "from sklearn.linear_model import Lasso                     #导入套索回归模型\n",
    "from sklearn.datasets import load_diabetes                 #导入糖尿病数据集\n",
    "from sklearn.model_selection import train_test_split       #导入划分样本的方法\n",
    "import numpy as np\n",
    "\n",
    "#将数据集划分为训练集和测试集\n",
    "x,y=load_diabetes().data,load_diabetes().target\n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=8)\n",
    "\n",
    "#训练模型\n",
    "model=Lasso(alpha=0.1,max_iter=100000)\n",
    "model.fit(x_train,y_train)\n",
    "a=np.sum(model.coef_!=0)    #模型特征属性不等于0的个数\n",
    "\n",
    "#评估模型\n",
    "#计算模型的预测准确率\n",
    "r21=model.score(x_train,y_train)\t#计算模型在训练集上的预测准确率\n",
    "r22=model.score(x_test,y_test)\t#计算模型在测试集上的预测准确率\n",
    "\n",
    "#输出模型的预测正确率\n",
    "print(\"模型在训练集上的预测准确率为：\",r21)            #输出模型在训练集上的预测准确率\n",
    "print(\"模型在测试集上的预测准确率为：\",r22)            #输出模型在测试集上的预测准确率\n",
    "print(\"套索回归使用的特征数为：\",a)   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c41808c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
